package com.zut.chat.service;

import com.zut.chat.dto.WebSocketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.stereotype.Service;

/**
 * Redis消息发布服务
 */
@Slf4j
@Service
@ConditionalOnProperty(name = "spring.redis.enabled", havingValue = "true", matchIfMissing = false)
public class RedisMessagePublisher {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ChannelTopic chatTopic;

    /**
     * 发布聊天消息到Redis
     */
    public void publishMessage(WebSocketMessage message) {
        try {
            redisTemplate.convertAndSend(chatTopic.getTopic(), message);
            log.debug("消息已发布到Redis频道: {}", message);
        } catch (Exception e) {
            log.error("发布消息到Redis失败", e);
        }
    }
}
